/**
 * @author harry
 * @date 2022/3/4/16:29
 */

package com.serviceOrchestration.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class ContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        applicationContext = ac;
    }

    /**
     * 从容器中获取bean
     * @param beanName bean的名字
     * @return 如果没有bean则返回null
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        try {
            return (T) applicationContext.getBean(beanName);
        } catch (BeansException e) {
            log.warn(e.getMessage());
            return null;
        }
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes == null ? null : attributes.getRequest();
    }
}
